package domain

import (
	"fmt"
	"github.com/sirupsen/logrus"
	"strconv"
	"time"
)

// 设置时间格式
const (
	timeFormat = "2006-01-02 15:04:05"
)

// TimeStr 自定义类型
type TimeStr time.Time

// TimeLong 自定义类型
type TimeLong time.Time

// UnmarshalJSON JsonDate反序列化
func (t *TimeStr) UnmarshalJSON(data []byte) (err error) {
	newTime, err := time.ParseInLocation("\""+timeFormat+"\"", string(data), time.Local)
	*t = TimeStr(newTime)
	return
}

// MarshalJSON JsonDate序列化
func (t TimeStr) MarshalJSON() ([]byte, error) {
	timeStr := fmt.Sprintf("\"%s\"", time.Time(t).Format(timeFormat))
	return []byte(timeStr), nil
}

// UnmarshalJSON JsonDate反序列化
func (t *TimeLong) UnmarshalJSON(data []byte) (err error) {
	defer func() {
		if err := recover(); err != nil {
			logrus.Println(err)
		}
	}()
	newTime, _ := strconv.ParseInt(string(data), 10, 64)
	*t = TimeLong(time.UnixMilli(newTime))
	return
}

// MarshalJSON JsonDate序列化
func (t TimeLong) MarshalJSON() ([]byte, error) {
	defer func() {
		if err := recover(); err != nil {
			logrus.Println(err)
		}
	}()
	timeStr := fmt.Sprintf("%d", time.Time(t).UnixMilli())
	return []byte(timeStr), nil
}
